﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Donal.Xms.Common;

namespace Donal.Xms.Web.api.payment.balance
{
    public partial class index : Web.UI.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string m = DESEncrypt.Decrypt(DTRequest.GetQueryString("m"));
            if (m.Trim() == "")
            {
                Response.Redirect(linkurl("error", "?msg=" + Utils.UrlEncode("出错了，支付参数有误！")));
                return;
            }

            string[] parameters = m.Split('_');

            if (parameters.Length != 2)
            {
                Response.Redirect(linkurl("error", "?msg=" + Utils.UrlEncode("出错了，支付参数有误！")));
                return;
            }

            //读取站点配置信息
            Model.sysconfig sysConfig = new BLL.sysconfig().loadConfig();
            string order_no = parameters[0].ToUpper();
            if (order_no == "")
            {
                Response.Redirect(linkurl("error", "?msg=" + Utils.UrlEncode("出错了，支付参数有误！")));
                return;
            }

            BLL.orders bll = new BLL.orders();
            Model.orders orders = bll.GetModel(order_no);

            if (orders == null)
            {
                Response.Redirect(linkurl("error", "?msg=" + Utils.UrlEncode("出错了，支付参数有误！")));
                return;
            }
            
            //检查是否已登录
            Model.users userModel = GetUserInfo();
            if (userModel == null)
            {
                Response.Redirect(linkurl("login")); //尚未登录
                return;
            }
                      

            if (userModel.company.amount < orders.order_amount)
            {
                Response.Redirect(linkurl("order_payment", "error", DESEncrypt.Encrypt(order_no + "_" + DateTime.Now.ToString()), DESEncrypt.Encrypt("信用余额不足"))); //账户的余额不足
                return;
            }

            if (order_no.StartsWith("SC")) //SC开头为商品订单
            {
                if (orders.payment_status < 2)//0未支付 1待支付 2已支付
                {
                    //更改订单状态
                    bool result1 = bll.UpdateField(order_no, "payment='3',payment_status=2,payment_time='" + DateTime.Now + "'", 3);
                    if (!result1)
                    {
                        Response.Redirect(linkurl("payment_complete", "error", DESEncrypt.Encrypt(order_no + "_" + DateTime.Now.ToString()), DESEncrypt.Encrypt("对不起，系统错误，更改订单状态失败！")));
                        return;
                    }                   
                }               

                //支付成功
                Response.Redirect(linkurl("payment_complete", "succeed", order_no));
                return;
            }
            
            Response.Redirect(linkurl("order_payment", "error", DESEncrypt.Encrypt(order_no + "_" + DateTime.Now.ToString()), DESEncrypt.Encrypt("对不起，找不到需要支付的订单类型！")));
            return;
        }
    }
}